//
//  SelPayMethodViewController.m
//  BaseProject
//
//  Created by 王洋 on 2020/7/29.
//  Copyright © 2020 王洋. All rights reserved.
//
#import <WXApi.h>
#import <AlipaySDK/AlipaySDK.h>

#import "OrderSegmentViewController.h"


#import "OrderSegmentViewController.h"

#import "SelPayMethodViewController.h"

@interface SelPayMethodViewController ()<RTNavigationItemCustomizable>

@property (nonatomic, assign) BOOL isFold;

@property (nonatomic, assign) SelPayMethodType payType;

@end

@implementation SelPayMethodViewController

-(void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"payResultNotification" object:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initView];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(payResultCallBack:) name:@"payResultNotification" object:nil];
    self.rt_navigationController.delegate = self;

}

- (UIBarButtonItem *)rt_customBackItemWithTarget:(id)target action:(SEL)action {
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setImage:[UIImage imageNamed:@"public_back_black"] forState:UIControlStateNormal];
    btn.frame = CGRectMake(0, 0, 50, 44);
    btn.imageEdgeInsets = UIEdgeInsetsMake(0, -30, 0, 0);
    [btn addTarget:target action:@selector(goNaviBack) forControlEvents:UIControlEventTouchUpInside];
    return [[UIBarButtonItem alloc] initWithCustomView:btn];
}

- (void)goNaviBack {
    
    for (UIViewController *vc in self.navigationController.viewControllers) {

        if ([vc isKindOfClass:[OrderSegmentViewController class]]) {
            [self.navigationController popViewControllerAnimated:YES];
            return;
        }
    }
    
    [self.navigationController popToRootViewControllerAnimated:NO];
}

-(void)payResultCallBack:(NSNotification *)Noti {
    
    BOOL isPaySuccess = [[Noti.userInfo objectForKey:@"resultStatus"] boolValue];
    NSString *resultMsg = [Noti.userInfo objectForKey:@"memo"];
    NSString *payType = [Noti.userInfo objectForKey:@"payType"];

    if (isPaySuccess && self.activeType.length > 0) {
        //锦鲤活动在支付成功后更新job状态
        if ([self.activeType isEqualToString:@"2"]) {
            JobModel *activationJob = [[BA_JobManager manager] getJobWithType:BA_JobManagerType_JLAct];
            activationJob.activationState = JobActivationType_finish;
            activationJob.triggerState = JobTriggerType_wait;
            [[BA_JobManager manager] updateJobWithModel:activationJob];
        }

    }
    
    [self loadPayResultViewWith:isPaySuccess Msg:resultMsg AndType:payType];
}

-(void)loadPayResultViewWith:(BOOL)payResult Msg:(NSString *)msg AndType:(NSString *)payType {
        
    if (payResult) {
        [SVProgressHUD showSuccessWithStatus:@"支付成功"];
        [SVProgressHUD dismissWithDelay:2];
        
        switch (self.entranceType) {
            case PayEntranceType_ser:{
                OrderSegmentViewController *vc = [[OrderSegmentViewController alloc] init];
                vc.selectIndex = 0;
                [self.navigationController pushViewController:vc animated:YES];
            } break;
            case PayEntranceType_pro:{
                OrderSegmentViewController *vc = [[OrderSegmentViewController alloc] init];
                vc.selectIndex = 1;
                [self.navigationController pushViewController:vc animated:YES];
            } break;
            case PayEntranceType_field:{
                OrderSegmentViewController *vc = [[OrderSegmentViewController alloc] init];
                vc.selectIndex = 2;
                [self.navigationController pushViewController:vc animated:YES];
            } break;
            case PayEntranceType_list:{
                
                for (UIViewController *vc in self.navigationController.viewControllers) {

                    if ([vc isKindOfClass:[OrderSegmentViewController class]]) {
                        [self.navigationController popToViewController:vc animated:YES];
                        return;
                    }
                }
                
//                [self.navigationController popViewControllerAnimated:YES];
            } break;
                
                
            default:
                break;
        }

    } else {
        
        [SVProgressHUD showSuccessWithStatus:msg];
        [SVProgressHUD dismissWithDelay:2];
    }
}

- (void)viewWillLayoutSubviews {
    
    [super viewWillLayoutSubviews];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.01 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [self.wechatControl pp_clipCorners:UIRectCornerTopLeft|UIRectCornerTopRight radius:10];
        [self.foldControl pp_clipCorners:UIRectCornerBottomLeft|UIRectCornerBottomRight radius:10];
        [self.payBtn pp_clipCorners:UIRectCornerAllCorners radius:self.payBtn.frame.size.height/2];
    });
}

- (void)initView {
    
    self.title = @"支付订单";
    self.isFold = YES;
    self.payType = SelPayMethodType_wechat;
    [self.selWechatPayBtn setImage:[UIImage imageNamed:@"common_sel"] forState:UIControlStateNormal];
    [self.selAlipayBtn setImage:[UIImage imageNamed:@"common_nor"] forState:UIControlStateNormal];
    
    if (self.model.overTime) {
        self.leaveTimeLab.text = [Utilities getTimeFromTimestamp:self.model.overTime];
    } else {
        self.leaveTimeLab.text = @"";
    }
    
    self.priceLab.text = [NSString stringWithFormat:@"¥%@",[Utilities changeDoubleToString:self.model.total]];
    self.contentLab.text = self.goodsModel.goodsName;
    
    self.alipayHeight.constant = CGFLOAT_MIN;
    [self.foldControl addGestureTapEventHandle:^(id  _Nonnull sender, UITapGestureRecognizer * _Nonnull gestureRecognizer) {
       
        self.isFold = !self.isFold;
        if (self.isFold) {
            self.alipayHeight.constant = CGFLOAT_MIN;
        } else {
            self.alipayHeight.constant = 68.0f;
        }
        
    }];
}

- (IBAction)selWechat:(id)sender {
    self.payType = SelPayMethodType_wechat;
    [self.selWechatPayBtn setImage:[UIImage imageNamed:@"common_sel"] forState:UIControlStateNormal];
    [self.selAlipayBtn setImage:[UIImage imageNamed:@"common_nor"] forState:UIControlStateNormal];
}

- (IBAction)selAlipay:(id)sender {
    self.payType = SelPayMethodType_alipay;
    [self.selWechatPayBtn setImage:[UIImage imageNamed:@"common_nor"] forState:UIControlStateNormal];
    [self.selAlipayBtn setImage:[UIImage imageNamed:@"common_sel"] forState:UIControlStateNormal];
}

- (IBAction)payAction:(id)sender {
    
    switch (self.payType) {
        case SelPayMethodType_wechat: {
            
            self.model.payType = @"1";

        } break;
        case SelPayMethodType_alipay: {
            
            self.model.payType = @"2";


        } break;
        default:
            break;
    }
    
    [self request_pay];
}

//调取微信支付
- (void)callWechatPayWithInfo:(NSDictionary *)orderInfo {

    PayReq *request = [[PayReq alloc] init];
    request.openID = [orderInfo objectForKey:@"appid"];
    request.partnerId =     [orderInfo objectForKey:@"partnerid"];
    request.prepayId =      [orderInfo objectForKey:@"prepayid"];
    request.package =       [orderInfo objectForKey:@"package"];
    request.nonceStr =      [orderInfo objectForKey:@"noncestr"];
    NSString *stamp =       [orderInfo objectForKey:@"timestamp"];
    request.timeStamp =     stamp.intValue;
    request.sign =          [orderInfo objectForKey:@"sign"];
    [WXApi sendReq:request completion:^(BOOL success) {
        
    }];
}

- (void)payWithOrderString:(NSString *)orderString {

    NSString *appScheme = @"com.ahrykj.Weddingg";
    [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
        NSString * isPaySuccess = @"0";
        NSString * msg = [resultDic objectForKey:@"memo"];;
        switch ([[resultDic objectForKey:@"resultStatus"] integerValue]) {
            case 6001: {
                isPaySuccess = @"0";
                msg = @"用户中途取消";
            } break;
            case 6002: {
                isPaySuccess = @"0";
                msg = @"网络连接出错";
            } break;
            case 6004: {
                isPaySuccess = @"0";
                msg = @"支付结果未知（有可能已经支付成功），请查询商户订单列表中订单的支付状态";
            } break;
            case 4000: {
                isPaySuccess = @"0";
                msg = @"订单支付失败";
            } break;
            case 8000: {
                isPaySuccess = @"0";
                msg = @"正在处理中，支付结果未知（有可能已经支付成功），请查询商户订单列表中订单的支付状态";
            } break;
            case 9000: {
                isPaySuccess = @"1";
                msg = @"订单支付成功";
            } break;
            default:
                break;
        }
        
        NSMutableDictionary *payDic = @{}.mutableCopy;
        [payDic setValue:msg forKey:@"memo"];
        [payDic setValue:msg forKey:@"msg"];
        [payDic setValue:@"alipay" forKey:@"payType"];
        [payDic setValue:isPaySuccess forKey:@"resultStatus"];
        [payDic setValue:[resultDic objectForKey:@"resultStatus"] forKey:@"code"];
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"payResultNotification" object:nil userInfo:payDic];
    }];
}

- (void)request_pay {
    
    NSMutableDictionary *dic = @{}.mutableCopy;
    dic = [self.model modelToJSONObject];

    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_Pay];

    WEAKSELF
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {

        if ([data isKindOfClass:[NSDictionary class]]) {
            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {
                NSDictionary *resultDic = [data valueForKey:@"data"];
                
                if (weakSelf.model.total == 0) {
                    //如果价格为0直接跳订单列表
                    switch (self.entranceType) {
                        case PayEntranceType_ser:{
                            OrderSegmentViewController *vc = [[OrderSegmentViewController alloc] init];
                            vc.selectIndex = 0;
                            [self.navigationController pushViewController:vc animated:YES];
                        } break;
                        case PayEntranceType_pro:{
                            OrderSegmentViewController *vc = [[OrderSegmentViewController alloc] init];
                            vc.selectIndex = 1;
                            [self.navigationController pushViewController:vc animated:YES];
                        } break;
                        case PayEntranceType_field:{
                            OrderSegmentViewController *vc = [[OrderSegmentViewController alloc] init];
                            vc.selectIndex = 2;
                            [self.navigationController pushViewController:vc animated:YES];
                        } break;
                        default:{
                            [self.navigationController popViewControllerAnimated:YES];
                        } break;
                    }
                    
                    return;
                }
                
                
                if ([resultDic isKindOfClass:[NSDictionary class]]) {

                    if ([resultDic.allKeys containsObject:@"appid"]) {
                        [weakSelf callWechatPayWithInfo:resultDic];
                    }
                    
                    if ([resultDic.allKeys containsObject:@"alipay"]) {
                        [weakSelf payWithOrderString:[resultDic valueForKey:@"alipay"]];
                    }
                }

                
            } else {
                [SVProgressHUD showErrorWithStatus:[data valueForKey:@"message"]];
                [SVProgressHUD dismissWithDelay:1];
            }
        }
        
        [SVProgressHUD dismissWithDelay:0.5];
        
    } FailedBlock:^(NSError * _Nonnull error) {
        
        [SVProgressHUD dismissWithDelay:0.5];

    }];
    
    
    
}


@end
